/*
 * @Author: jingfuu@163.com
 * @Date: 2024-09-20 11:07:34
 * @LastEditTime: 2024-12-11 13:33:35
 * @Description: file content
 */
import {
  Injectable,
  CanActivate,
  ExecutionContext,
  ForbiddenException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { ClsService } from 'nestjs-cls';
import { Constants } from '../Constants';
import { UserSession } from '../UserSession';
import { ConfigService } from '@nestjs/config';
import { PreAuthorize } from '../decorator/PreAuthorizeDecorator';

@Injectable()
export class PreAuthorizeGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private cls: ClsService,
    private configService: ConfigService,
  ) {}

  canActivate(context: ExecutionContext): boolean {
    const permissions = this.reflector.get(PreAuthorize, context.getHandler());
    //管理员默认有该注解标识接口权限
    const permList = ['*:*:*'];
    if (!permissions) return true;
    if (typeof permissions === 'string') {
      permList.push(permissions);
    }
    if (typeof permissions === 'object' && Array.isArray(permissions)) {
      permList.push(...permissions);
    }
    const userSession = this.cls.get<UserSession>(Constants.USER_SESSION);
    if (permList && permList.length > 0 && userSession) {
      const userPermissions = userSession.permissions;
      return permList.some((perm) => userPermissions.includes(perm));
    }
    throw new ForbiddenException();
  }
}
